<?php

namespace app\api\controller;

use app\admin\model\Appform;
use app\admin\model\Appfuns;
use app\admin\model\Business;
use app\admin\model\Comkeywords;
use app\admin\model\Comment;
use app\admin\model\Jumpurl;
use app\admin\model\Onecate;
use app\admin\model\Orders;
use app\admin\model\Pages;
use app\admin\model\Reports;
use app\common\library\Exports;
use ba\Tree;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\controller\Frontend;
use app\common\library\token\TokenExpirationException;

class Index extends Frontend
{
    protected array $noNeedLogin = ['reportSave'];
    protected array $noNeedPermission = ["*"];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 前台和会员中心的初始化请求
     * @throws Throwable
     */
    public function index(): void
    {
        $menus = [];
        if ($this->auth->isLogin()) {
            $rules = [];
            $userMenus = $this->auth->getMenus();

            // 首页加载的规则，验权，但过滤掉会员中心菜单
            foreach ($userMenus as $item) {
                if ($item['type'] == 'menu_dir') {
                    $menus[] = $item;
                } elseif ($item['type'] != 'menu') {
                    $rules[] = $item;
                }
            }
            $rules = array_values($rules);
        } else {
            // 若是从前台会员中心内发出的请求，要求必须登录，否则会员中心异常
            $requiredLogin = $this->request->get('requiredLogin/b', false);
            if ($requiredLogin) {

                // 触发可能的 token 过期异常
                try {
                    $token = get_auth_token(['ba', 'user', 'token']);
                    $this->auth->init($token);
                } catch (TokenExpirationException) {
                    $this->error(__('Token expiration'), [], 409);
                }

                $this->error(__('Please login first'), [
                    'type' => $this->auth::NEED_LOGIN
                ], $this->auth::LOGIN_RESPONSE_CODE);
            }

            $rules = Db::name('user_rule')
                ->where('status', '1')
                ->where('no_login_valid', 1)
                ->where('type', 'in', ['route', 'nav', 'button'])
                ->order('weigh', 'desc')
                ->select()
                ->toArray();
            $rules = Tree::instance()->assembleChild($rules);
        }
        $appfuns = (new Appfuns())
            ->where([
                ['status', '=', 1],
            ])
            ->whereNotIn('id', [3, 4])
            ->order('weigh', 'desc')
            ->select();
        $this->success('', [
            'site' => [
                'siteName' => get_sys_config('site_name'),
                'site_notice' => get_sys_config('site_notice'),
                'recordNumber' => get_sys_config('record_number'),
                'version' => get_sys_config('version'),
                'cdnUrl' => full_url(),
                'upload' => keys_to_camel_case(get_upload_config(), ['max_size', 'save_name', 'allowed_suffixes', 'allowed_mime_types']),
            ],
            'openMemberCenter' => Config::get('buildadmin.open_member_center'),
            'rules' => $rules,
            'menus' => $menus,
            'appfuns' => ['data' => $appfuns]
        ]);
    }


    public function appfuns()
    {
        $id = $this->request->param('id/d');
        $rows = (new Appfuns())
            ->where([
                ['status', '=', 1],
                ['id', '=', $id],
            ])
            ->find();
        $funitem = (new Appform())->where([
            ['status', '=', 1],
            ['appfuns_id', '=', $id]
        ])
            ->order('weigh', 'desc')
            ->select();
        foreach ($funitem as &$item) {
            $item['value'] = '';
        }
        $fastinput = $rows['fastinput'];
        $this->success('', [
            'approw' => $rows,
            'fastinput' => $fastinput,
            'site' => [
                'change_rate' => get_sys_config('change_rate')
            ],
            'appform' => $funitem,
            'userinfo' => $this->auth->getUserInfo(),
        ]);
    }

    public function query_business()
    {
        $list = (new Business())
            ->where([
                ['status', '=', 1],
            ])
            ->order('weigh', 'desc')
            ->paginate();// 可以直接换成 paginate 下面要切换
        $this->success('', ['data' => $list]);
    }

    public function business()
    {
        $id = $this->request->param('id/d');
        $rows = (new Business())
            ->where([
                ['status', '=', 1],
                ['id', '=', $id],
            ])
            ->find();
        $funitem = (new Appform())->where([
            ['status', '=', 1],
            //['appfuns_id', '=', $id]
        ])
            ->order('weigh', 'desc')
            ->select();
        foreach ($funitem as &$item) {
            $item['value'] = '';
        }
        $this->success('', [
            'approw' => $rows,
            'fastinput' => [
                ['id' => 1, 'value' => 500],
                ['id' => 2, 'value' => 1000],
                ['id' => 3, 'value' => 5000],
                ['id' => 4, 'value' => 10000],
                ['id' => 5, 'value' => 50000],
                ['id' => 6, 'value' => 100000]
            ],
            'site' => [
                'change_rate' => get_sys_config('change_rate')
            ],
            'appform' => $funitem,
            'userinfo' => $this->auth->getUserInfo(),
        ]);

    }


    /*
     * 举报保存
    */
    public function reportSave()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            (new Reports())->create($params);
            $this->success('举报成功');
        }
        $group_radio = $this->request->param('group_radio');
        $onecate = (new Onecate())->where([
            ['group_radio', '=', $group_radio],
        ])->select();
        $this->success('信息', [
            'onecate' => $onecate,
        ]);
    }

    /*
     * 举报笔记评论保存
    */
    public function commentSave()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params['user_id'] = $this->auth->id;
            (new Comment())->create($params);
            $this->success('举报成功');
        }
        //时间:opt0=5分钟,opt1=10分钟,opt2=30分钟,opt3=24小时
        $keyws = (new Comkeywords())->select();
        $this->success('信息', [
            'keyws' => $keyws,
            'radioarr' => [
                ['id' => 'opt0', 'name' => '5分钟'],
                ['id' => 'opt1', 'name' => '10分钟'],
                ['id' => 'opt2', 'name' => '30分钟'],
                ['id' => 'opt3', 'name' => '24小时'],
            ]
        ]);
    }

    public function pageinfo()
    {
        $row = (new Pages())->where('id', $this->request->param('id/d'))->find();
        $this->success('', $row);
    }

    public function submitPay()
    {
        $pay_money = $this->request->param('pay_money');
        $appfuns_id = $this->request->param('appfuns_id/d');
        $appform = $this->request->param('appform');
        if (empty($pay_money)) {
            $this->error('金额不能为空');
        }
        $rows = (new Appfuns())->where('id', '=', $appfuns_id)->find();
        $discount=$rows['discount'];
        if ($rows) {
            //  $pay_money=bcmul($pay_money*(1-$rows['discount']/100),1,2);
        }
        $radio=$this->request->param('radio');
        $product_money=0;// 人民币
        if($radio=='opt0'){
            $query_row=(new Business())->where('id', '=', $appfuns_id)->find();
            $product_money=$query_row['prices'];
            $discount=$query_row['discount'];
        }else if($radio=='opt1'){
            $product_money=$pay_money;
        }
        $radio=$rows['order_tag']?$rows['order_tag']:'opt1';
        //打折
        $discount_money=$product_money*$discount/100;
        $orderpay=$product_money-$discount_money;
        $pay_money=$orderpay;

        $pay_dollar=bcdiv($orderpay,get_sys_config('change_rate'),2);// 支付美元dollar
        $noinfo = (new \app\admin\model\User())->where('id', '=', $this->auth->id)->find();
        $last_money = $noinfo['money']- $noinfo['unmoney'];
        if ($pay_dollar > $last_money) {
            $this->error('余额不足', $last_money);
        }
        $order_no = (new Orders())->orderNum();
        (new Orders())->insert([
            'user_id' => $this->auth->id,
            'order_no' => $order_no,
            'check_status' => 0,
            'assign_status' => 0,
            'pay_money' => $pay_money,
            'create_time' => time(),
            'pay_dollar' => $pay_dollar,
            'radio' => $radio,
            'cxstatus' => 0,
            'status' => 0,
            'dollar_rate' => get_sys_config('change_rate'),
            'appfuns_id' => $appfuns_id,
            'upimgs' => $this->request->param('upimgs'),
            'provide_clues' => $this->request->param('provide_clues'),
            'textarea' => html_entity_decode(stripslashes($appform))
        ]);
        $noinfo->save([
            'unmoney' => $pay_dollar + $noinfo['unmoney']
        ]);
        $this->success('成功', [
            $pay_money, bcmul($pay_money * (1 - $rows['discount'] / 100), 1, 2)
        ]);
    }
}